Skip to content

extendable schema type#183

Open
newash wants to merge 2 commits intotdegrunt:masterfrom
newash:patch-1
Open

extendable schema type#183
newash wants to merge 2 commits intotdegrunt:masterfrom
newash:patch-1

Conversation

@newash
Copy link

@newash newash commented Aug 12, 2016

With the existing type definition it was not possible to add extra fields to the schema (such as "default").
Using generics now anything can be added.

With my current project it's kinda necessary, so it would be nice of you if you could pull it in. Thanks!

With the existing type definition it was not possible to add extra fields to the schema (such as "default").
Using generics now anything can be added.
@awwright
Copy link
Collaborator

@newash Could you provide a quick code example of how this would be used, and maybe how it runs for you with and without the patch?

Thanks!

@newash
Copy link
Author

newash commented Aug 14, 2016

@awwright Sure, this is my code for generating defaults:

export interface MySchema extends Schema<MySchema> {
  default: any;
}

const validator = new Validator<MySchema>();

function addDefaults(instance: any, schema: MySchema): any {
  if (schema.default !== undefined && instance === undefined) {
    return schema.default;
  }
  return instance;
}

function validate(instance: any,  uri: string, extension: RewriteFunction<MySchema>): ValidatorResult<MySchema> {
  return validator.validate(instance, uri, { rewrite: extension });
}

export function createDefaults(instance: any,  uri: string): any {
  let result: ValidatorResult<MySchema> = validate(instance, uri, addDefaults);
  if (!result.valid)
    throw "something went wrong with model creation";
  return result.instance;
}

Without the generics, the schema.default expression in the addDefaults function throws a compilation error saying there's no "default" attribute of Schema. And I had to decorate all interfaces for the RewriteFunction to get the proper tying.

I know it's not a small change and I'd be the happiest if you knew a neater solution, but I'm afraid this is the neat one.

this is a non-typesafe solution but less obstructive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants